package com.kele.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author kele
 * @date 2021/10/12 16:05
 * @description ForkJoin
 *
 * 三种方式比较球和任务
 */
public class ForkJoinTest extends RecursiveTask<Long> {
    private Long start;
    private Long end;
    // 临界值
    private Long temp = 1000L;
    public ForkJoinTest(Long start, Long end) {
        this.start = start;
        this.end = end;
    }
    @Override
    protected Long compute() {
        if ((end-start)<temp){
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else {
            long middle = (start + end) / 2;
            ForkJoinTest task1 = new ForkJoinTest(start, middle);
            task1.fork(); // 拆分任务，把任务压入线程队列
            ForkJoinTest task2 = new ForkJoinTest(middle+1, end);
            task2.fork(); // 拆分任务，把任务压入线程队列
            return task1.join() + task2.join();
        }
    }
}
